#!/usr/bin/env bash
#
# Delete the "guest" default user and replace it with a Zulip user
# with a real password
set -eu

# If the RabbitMQ distribution cookie is insecure, reset it and
# restart RabbitMQ.
"$(dirname "$0")/generate-rabbitmq-cookie"

RABBITMQ_USERNAME=$("$(dirname "$0")/../get-django-setting" RABBITMQ_USERNAME)
RABBITMQ_PASSWORD=$("$(dirname "$0")/../get-django-setting" RABBITMQ_PASSWORD)
RABBITMQ_VHOST=$("$(dirname "$0")/../get-django-setting" RABBITMQ_VHOST)

tries=0
while ((tries < 30)) && ! rabbitmqctl ping -q 2>/dev/null; do
    ((tries++)) || echo "Waiting for RabbitMQ to start up..."
    sleep 1
done
rabbitmqctl await_startup

rabbitmqctl delete_user "$RABBITMQ_USERNAME" || true
rabbitmqctl delete_user zulip || true
rabbitmqctl delete_user guest || true
rabbitmqctl add_user "$RABBITMQ_USERNAME" "$RABBITMQ_PASSWORD"
rabbitmqctl set_user_tags "$RABBITMQ_USERNAME" administrator
if ! rabbitmqctl list_vhosts --no-table-headers --quiet | grep -qx "$RABBITMQ_VHOST"; then
    rabbitmqcql add_vhost "$RABBITMQ_VHOST"
fi
rabbitmqctl set_permissions -p "$RABBITMQ_VHOST" "$RABBITMQ_USERNAME" '.*' '.*' '.*'
